<template>
    <el-dialog :title="titleMap[mode]" v-model="visible" :width="1500" :close-on-click-modal="false" :close-on-press-escape="mode != 'show' ? false : true" destroy-on-close @closed="$emit('closed')" align-center>
        <el-form :model="form" :rules="rules" :disabled="mode=='show'" label-width="100" ref="dialogForm">
            <el-row :gutter="1">
                <el-col :span="6">
                    <el-form-item label="调拨单号" prop="allocation_code">
                        <el-input v-model="form.allocation_code" placeholder="调拨单号(不填写自动生成)" clearable></el-input>
                    </el-form-item>
                </el-col>
                <el-col :span="6">
                    <el-form-item label="调拨日期" prop="allocation_date">
                        <el-date-picker v-model="form.allocation_date" type="date" placeholder="请选择日期" :value-format="'YYYY-MM-DD'" style="width:100%"/>
                    </el-form-item>
                </el-col>
                <el-col :span="6">
                    <el-form-item label="调出仓库" prop="out_ware_id">
                        <el-select v-model="form.out_ware_id" filterable style="width: 100%" placeholder="调出仓库" @change="outChange" clearable>
                            <el-option v-for="item in wareList" :key="item.id" :label="item.ware_name" :value="item.id"/>
                        </el-select>
                    </el-form-item>
                </el-col>
                <el-col :span="6">
                    <el-form-item label="调入仓库" prop="new_ware_id">
                        <el-select v-model="form.new_ware_id" filterable style="width: 100%" placeholder="调入仓库" @change="newChange" clearable>
                            <el-option v-for="item in wareList" :key="item.id" :label="item.ware_name" :value="item.id"/>
                        </el-select>
                    </el-form-item>
                </el-col>
                <el-col :span="24">
                    <el-form-item label="备注" prop="remark">
                        <el-input v-model="form.remark" placeholder="请输入备注" type="textarea" clearable></el-input>
                    </el-form-item>
                </el-col>
            </el-row>
            <el-form-item label="调拨商品清单" prop="detail">
                <el-button type="primary" size="small" icon="el-icon-plus" @click="checkProduct">选择商品</el-button>
                <sc-form-table ref="table" v-model="form.detail" :addTemplate="addTemplate" placeholder="暂无数据" height="400" hideAdd show-summary>
                    <el-table-column label="商品名称" align="center">
                        <template #default="scope">
                            {{ scope.row.goods_name }}
                        </template>
                    </el-table-column>
                    <el-table-column label="商品编号" align="center">
                        <template #default="scope">
                            {{ scope.row.goods_code }}
                        </template>
                    </el-table-column>
					<el-table-column label="商品图片" align="center">
						<template #default="scope">
							<el-image v-if="scope.row.goods_image" style="width: 30px; height: 30px; border-radius: 5px;" :src="scope.row.goods_image" :preview-src-list="[scope.row.goods_image]" preview-teleported="true" hide-on-click-modal align="center"></el-image>
						</template>
					</el-table-column>
                    <el-table-column label="商品单位" align="center" prop="unit_name"></el-table-column>
                    <el-table-column label="数量" prop="number" align="center">
                        <template #default="scope">
                            <el-input v-model="scope.row.number" placeholder="数量" @focus="onFocus($event)"></el-input>
                        </template>
                    </el-table-column>
                    <!-- <el-table-column label="单价" prop="price" align="center">
                        <template #default="scope">
                            <el-input v-model="scope.row.price" placeholder="单价" @focus="onFocus($event)"></el-input>
                        </template>
                    </el-table-column>
                    <el-table-column label="小计" prop="total_price" align="center">
                        <template #default="scope">
                            <el-input v-model="scope.row.total_price" placeholder="小计" readonly></el-input>
                        </template>
                    </el-table-column> -->
                    <el-table-column label="备注" align="center">
                        <template #default="scope">
                            <el-input v-model="scope.row.remark" placeholder="备注"></el-input>
                        </template>
                    </el-table-column>
                </sc-form-table>
            </el-form-item>
            <!-- <el-form-item label="附件" prop="enclosure">
                <sc-upload-file v-model="form.enclosure" :is_same_name="1">
                    <el-button type="primary" icon="el-icon-upload">选择文件</el-button>
                </sc-upload-file>
            </el-form-item> -->
        </el-form>
        <template #footer>
            <el-button @click="visible=false">取 消</el-button>
            <el-button v-if="mode!='show'" type="primary" :loading="isSaveing" @click="submit()">保 存</el-button>
        </template>
    </el-dialog>
    <select-stock v-if="dialog.save" ref="saveDialog" @success="handleSuccess" @closed="dialog.save=false" :query="{ware_id:form.out_ware_id,allocation:1}"></select-stock>
</template>

<script>
import selectStock from '../stock/selectStock.vue';

export default {
    components: {selectStock},
    emits: ['success', 'closed'],
    data() {
        return {
        mode: "add",
        titleMap: {
            add: '新增',
            edit: '编辑',
            show: '查看',
        },
        visible: false,
        isSaveing: false,
        form: {
            id: "",
            allocation_code: "",
            allocation_date: this.moment().format('YYYY-MM-DD'),
            out_ware_id: "",
            new_ware_id: "",
            remark:'',
            detail: [],
        },
        rules: {
            out_ware_id: [
            {required: true, message: '请选择调出仓库'}
            ],
            new_ware_id: [
            {required: true, message: '请选择调入仓库'}
            ],
            allocation_date: [
            {required: true, message: '请选择调拨日期'}
            ],
        },
        addTemplate: {},
        wareList: [],
        dialog: {
            save: false,
        },
        }
    },
    mounted() {
        this.getWare()
    },
    methods: {
        //显示
        open(mode = 'add') {
            this.mode = mode;
            this.visible = true;
            return this
        },
        //表单提交方法
        submit() {
            this.$refs.dialogForm.validate(async (valid) => {
                if (valid) {
                this.isSaveing = true;
                var res = [];
                if (this.form.id) {
                    res = await this.$API.procure.diaobo.edit.post(this.form);
                } else {
                    res = await this.$API.procure.diaobo.add.post(this.form);
                }
                this.isSaveing = false;
                if (res != '') {
                    if (res.code == 1) {
                    this.$emit('success', this.form, this.mode)
                    this.visible = false;
                    this.$message.success("操作成功")
                    } else {
                    this.$alert(res.message, "提示", {type: 'error'})
                    }
                }
                }
            })
        },
        //表单注入数据
        async setData(data) {
            this.form.id = data.id
            var res = await this.$API.procure.diaobo.detail.get({id: data.id});
            this.form.allocation_code = res.data.allocation_code
            this.form.allocation_date = res.data.allocation_date
            this.form.out_ware_id = res.data.out_ware_id
            this.form.new_ware_id = res.data.new_ware_id
            this.form.remark = res.data.remark
            let array = []
            res.data.detail.map(item => {
                array.push({
                id: item.id,
                goods_id: item.goods_id,
                goods_name: item.goods && item.goods.goods_name,
					goods_image: item.goods && item.goods.goods_image,
                unit_name: item.goods && item.goods.unit.unit_name,
                goods_code: item.goods && item.goods.goods_code,
                number: item.number,
                // price:item.price,
                // total_price:item.total_price,
                remark: item.remark,
                })
            })
            this.form.detail = array
        },
        // 选择商品
        checkProduct() {
            if (this.form.out_ware_id == '') {
                this.$message.error("请先选择调出仓库")
            } else {
                this.dialog.save = true
                this.$nextTick(() => {
                this.$refs.saveDialog.open('add')
                })
            }
        },
        // 选择商品返回
        handleSuccess(data) {
            let array = []
            data.map((item) => {
                array.push({
                goods_id: item.goods.id,
                goods_name: item.goods.goods_name,
					goods_image: item.goods.goods_image,
                unit_name: item.goods.unit.unit_name,
                mater_code: item.goods.material_code,
                goods_code: item.goods.goods_code,
                })
            })
            let existingIds = this.form.detail.map(item => item.goods_id);
            for (let i = array.length - 1; i >= 0; i--) {
                if (existingIds.includes(array[i].goods_id)) {
                array.splice(i, 1);
                }
            }
            this.form.detail = [...this.form.detail, ...array]
        },
        // 获取仓库
        async getWare() {
            var res = await this.$API.goods.ware.all.get();
            this.wareList = res.data;
        },
        onFocus(event) {
            event.target.select();
        },
        totalCompute() {
            this.form.detail.map(item => {
                if (item.price && item.number) {
                item.total_price = (Number(item.number) * Number(item.price)).toFixed(2)
                }
            })
        },
        outChange() {
            this.form.detail = []
        },
        newChange(e) {
            if (this.form.out_ware_id == e) {
                this.$message.error("调入仓库不能与调出仓库相同")
                this.form.new_ware_id = ''
            }
        },
    }
}
</script>

<style>
</style>
